package com.centling.smartSealForPhone.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.application.SmartSeal;
import com.centling.smartSealForPhone.bean.ApplyRejectedBean;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.bean.SealApplyIdBean;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.constants.UserType;
import com.centling.smartSealForPhone.db.DbControl;
import com.centling.smartSealForPhone.db.ImageBean;
import com.centling.smartSealForPhone.service.UploadImageService;
import com.centling.smartSealForPhone.utils.BitmapUtils;
import com.centling.smartSealForPhone.utils.FilePathUtils;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.PhoneNumCheck;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.centling.smartSealForPhone.utils.TextLengthWatch;
import com.centling.smartSealForPhone.widget.ShSwitchView;
import com.example.localalbum.common.ImageUtils;
import com.example.localalbum.common.LocalImageHelper;
import com.example.localalbum.ui.ImageScrollView;
import com.example.localalbum.ui.LocalAlbum;
import com.google.gson.Gson;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class ApplySealActivity
        extends TitleBarActivity
        implements View.OnClickListener {
    private final int APPLY_MODE_COUNT = 1000;
    private final int APPLY_MODE_TIME = 2000;

    private final int CAMERA_USER = 1001;
    private final int GALLERY_USER = 3001;

    private final int APPLY_SEAL_TYPE = 4001;
    private final int APPLY_SEAL_REASON = 2001;
    private final int APPLY_SEAL_APPROVAL = 5001;

    private Long exitTime = 0L;
    private LinearLayout llApplySealRootLayout;

    private TextView tvApplySealSealModeLimitCount;
    private TextView tvApplySealSealModeLimitTime;

    private LinearLayout llName;
    private EditText etName;
    private LinearLayout llPhone;
    private EditText etPhone;
    private EditText etStampNum;
    private TextView tvStampTime;
    private TextView tvStampTimeStartTime;
    private TextView tvStampTimeEndTime;

    private ImageView ivAddUserPic;
    private LinearLayout llAddUserPic;
    private Spinner spUsers;

    private List<String> userPathList = new ArrayList<>();
    private String imagePath;

    private String applySealTypeId = "";
    private LinearLayout llChooseType;
    private TextView tvChooseType;
    private LinearLayout llChooseTypeNeed;
    private ShSwitchView shSwitchView;

    private String applySealReasonId;
    private LinearLayout llReason;
    private TextView tvReason;
    private String applySealApprovalId;
    private TextView tvApprovalTips;
    private LinearLayout llApproval;
    private TextView tvApproval;
    private EditText etReason;
    private TextView tvSubmit;

    private TextView tvPicNum;
    private TextView lengthLimit;

    private ImageScrollView imageScrollView;

    private int applyMode = APPLY_MODE_COUNT;

    private boolean isCommonUser = false;
    private boolean isMachineUser = false;

    private String sealApplyId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_seal);

        setTitleBarText("用印申请");

        LoginBean loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON),
                LoginBean.class);
        isCommonUser = TextUtils.equals(UserType.EQUIP_COMMON_USER,
                SPUtil.getString(SPConstants.USER_TYPE));
        isMachineUser = TextUtils.equals("0", loginBean.getEquipRegisterInfo().getEquipType());

        initView();

        LocalImageHelper.getInstance().setTotalSize(100);

        dealWithRejected();
    }

    /**
     * 初始化
     * initView
     */
    private void initView() {
        llApplySealRootLayout = findViewById(R.id.ll_apply_seal_root_layout);

        tvApplySealSealModeLimitCount = findViewById(
                R.id.tv_apply_seal_seal_mode_limit_count);
        tvApplySealSealModeLimitTime = findViewById(
                R.id.tv_apply_seal_seal_mode_limit_time);

        tvApplySealSealModeLimitCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvApplySealSealModeLimitCount.setSelected(true);
                tvApplySealSealModeLimitTime.setSelected(false);
                tvApplySealSealModeLimitCount.setTextColor(
                        ContextCompat.getColor(mContext, R.color.white));
                tvApplySealSealModeLimitTime.setTextColor(
                        ContextCompat.getColor(mContext, R.color.blue1));
                applyMode = APPLY_MODE_COUNT;

                llApplySealRootLayout.getChildAt(4).setVisibility(View.VISIBLE);
                llApplySealRootLayout.getChildAt(5).setVisibility(View.VISIBLE);
                llApplySealRootLayout.getChildAt(6).setVisibility(View.GONE);
                llApplySealRootLayout.getChildAt(7).setVisibility(View.GONE);
            }
        });
        tvApplySealSealModeLimitTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvApplySealSealModeLimitCount.setSelected(false);
                tvApplySealSealModeLimitTime.setSelected(true);
                tvApplySealSealModeLimitCount.setTextColor(
                        ContextCompat.getColor(mContext, R.color.blue1));
                tvApplySealSealModeLimitTime.setTextColor(
                        ContextCompat.getColor(mContext, R.color.white));
                applyMode = APPLY_MODE_TIME;

                llApplySealRootLayout.getChildAt(6).setVisibility(View.VISIBLE);
                llApplySealRootLayout.getChildAt(7).setVisibility(View.VISIBLE);
                llApplySealRootLayout.getChildAt(4).setVisibility(View.GONE);
                llApplySealRootLayout.getChildAt(5).setVisibility(View.GONE);
            }
        });
        tvApplySealSealModeLimitCount.performClick();

        llName = findViewById(R.id.ll_apply_seal_name);
        etName = findViewById(R.id.et_apply_seal_name);
        llPhone = findViewById(R.id.ll_apply_seal_phone);
        etPhone = findViewById(R.id.et_apply_seal_phone);
        etStampNum = findViewById(R.id.et_apply_seal_stamp_num);
        tvStampTime = findViewById(R.id.tv_apply_seal_stamp_time);
        tvStampTimeStartTime = findViewById(R.id.tv_apply_seal_stamp_start_time);
        tvStampTimeEndTime = findViewById(R.id.tv_apply_seal_stamp_end_time);
        tvPicNum = findViewById(R.id.tv_apply_seal_pic_num);
        lengthLimit = findViewById(R.id.tv_apply_number_limit);
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                etPhone.setText("");
            }
        });

        llAddUserPic = findViewById(R.id.ll_apply_seal_user_photo);
        ivAddUserPic = findViewById(R.id.iv_apply_seal_add_user_pic);

        spUsers= findViewById(R.id.sp_apply_seal_users);
        final List<String> list = DbControl.getInstance().selectFiveUsers();
        String[] users=list.toArray(new String[list.size()]);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, users);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spUsers.setAdapter(adapter);
        spUsers.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String[] info=list.get(position).split(" ");
                etName.setText(info[0]);
                etPhone.setText(info[1]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (!isCommonUser) {
            llName.setVisibility(View.VISIBLE);
            llPhone.setVisibility(View.VISIBLE);
            llAddUserPic.setVisibility(View.VISIBLE);
        } else {
            etName.setText(SPUtil.getString(SPConstants.REAL_NAME));
            etPhone.setText(SPUtil.getString(SPConstants.PHONE));
        }

        llChooseType = findViewById(R.id.ll_apply_seal_choose_seal_type);
        tvChooseType = findViewById(R.id.tv_apply_seal_choose_seal_type);
        llChooseTypeNeed = findViewById(R.id.ll_apply_seal_choose_seal_type_need);
        shSwitchView = findViewById(R.id.sw_apply_seal_choose_seal_type_need);
        shSwitchView.setOn(true);
        llChooseType.setVisibility(isCommonUser ? View.VISIBLE : View.GONE);
        llChooseTypeNeed.setVisibility(isMachineUser ? View.VISIBLE : View.GONE);

        llReason = findViewById(R.id.ll_apply_seal_reason);
        tvReason = findViewById(R.id.tv_apply_seal_reason);
        tvApprovalTips = findViewById(R.id.tv_apply_seal_approval_tips);
        llApproval = findViewById(R.id.ll_apply_seal_approval);
        tvApproval = findViewById(R.id.tv_apply_seal_approval);

        if (!TextUtils.equals(BuildConfig.FLAVOR, "publicCloud")) {
            tvApprovalTips.setVisibility(View.VISIBLE);
            llApproval.setVisibility(View.VISIBLE);
        }

        etReason = findViewById(R.id.et_apply_seal_reason);
        tvSubmit = findViewById(R.id.tv_apply_seal_submit);

        tvStampTime.setOnClickListener(this);
        tvStampTimeStartTime.setOnClickListener(this);
        tvStampTimeEndTime.setOnClickListener(this);
        ivAddUserPic.setOnClickListener(this);
        llChooseType.setOnClickListener(this);
        llReason.setOnClickListener(this);
        llApproval.setOnClickListener(this);
        tvSubmit.setOnClickListener(this);

        imageScrollView = findViewById(R.id.isv_picture);

        etReason.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});
        etReason.addTextChangedListener(new TextLengthWatch(100));
        etReason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                lengthLimit.setText(
                        String.format(getString(R.string.number_limit_100), s.toString().length()));
                if (s.toString().length() == 100) {
                    lengthLimit.setTextColor(Color.RED);
                } else {
                    lengthLimit.setTextColor(Color.BLACK);
                }
            }
        });

        imageScrollView.setOnDeleteListener(new ImageScrollView.OnDeleteListener() {
            @Override
            public void onDelete(final int pos) {
                ShowDialog.showSelectDialog(mContext, "删除图片", "删除这张图片以重新添加", "", new View
                        .OnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(
                                imageScrollView.getFiles().get(pos).getApplyDocPicId())) {
                            imageScrollView.getFiles().remove(pos);
                            imageScrollView.getAdapter().notifyDataSetChanged();
                            tvPicNum.setText("文件拍照（已拍" + imageScrollView.getFiles()
                                    .size() + "张，最多100张文件图片）");
                            LocalImageHelper.getInstance().setCurrentSize(
                                    imageScrollView.getFiles().size());
                        } else {
                            sendRequestToDeleteFile(
                                    imageScrollView.getFiles().get(pos).getApplyDocPicId(),
                                    pos);
                        }
                    }
                });
            }
        });
        imageScrollView.setOnAddListener(new ImageScrollView.OnAddListener() {
            @Override
            public void onClick() {
                etName.clearFocus();
                etPhone.clearFocus();
                etStampNum.clearFocus();
                etReason.clearFocus();
                LocalImageHelper.getInstance().getCheckedItems().clear();
                LocalImageHelper.getInstance().setCurrentSize(imageScrollView.getFiles().size());
                startActivityForResult(new Intent(mContext, LocalAlbum.class),
                        ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP);
            }
        });
    }

    /**
     * 删除图片
     * sendRequestToDeleteFile
     *
     * @param id  sealApplyId
     * @param pos image position
     */
    private void sendRequestToDeleteFile(String id, final int pos) {
        mProcessDialog.setTitle("正在同步服务器").showNormal();
        Map<String, String> params = new HashMap<>();
        params.put("applyDocPicId", id);
        deleteJsonEnqueue(String.format(Locale.CHINA, UrlConstants.APPLY_STAMP_REJECTED_DELETE, id),
                params, new OkHttpUtil.NetCallBack() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        imageScrollView.getFiles().remove(pos);
                        imageScrollView.getAdapter().notifyDataSetChanged();
                        tvPicNum.setText(
                                "文件拍照（已拍" + imageScrollView.getFiles().size() + "张，最多100张文件图片）");
                        LocalImageHelper.getInstance().setCurrentSize(
                                imageScrollView.getFiles().size());
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
    }

    /**
     * 驳回处理
     * dealWithRejected
     */
    private void dealWithRejected() {
        sealApplyId = getIntent().getStringExtra("sealApplyId");
        if (TextUtils.isEmpty(sealApplyId)) {
            return;
        }
        mProcessDialog.setTitle("正在获取申请信息").showWithCancel();
        getEnqueue(String.format(Locale.CHINA, UrlConstants.APPLY_STAMP_REJECTED, sealApplyId),
                new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        mProcessDialog.dismiss();
                        ApplyRejectedBean applyRejectedBean = new Gson().fromJson(json,
                                ApplyRejectedBean.class);
                        setData(applyRejectedBean);
                    }

                    @Override
                    public void onFailed(String reason) {
                        mProcessDialog.dismiss();
                        ShowToast.shortTime(reason);
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void setData(ApplyRejectedBean applyRejectedBean) {
        if (TextUtils.equals(applyRejectedBean.getApplyType(), "COUNT_LIMIT")) {
            tvApplySealSealModeLimitCount.performClick();
            etStampNum.setText(applyRejectedBean.getApplyTimes());
            tvStampTime.setText(applyRejectedBean.getApplyDate());
        } else {
            tvApplySealSealModeLimitTime.performClick();
            tvStampTimeStartTime.setText(applyRejectedBean.getApplyStartTime());
            tvStampTimeEndTime.setText(applyRejectedBean.getApplyEndTime());
        }
        etName.setText(applyRejectedBean.getApplicantUserName());
        etPhone.setText(applyRejectedBean.getPhone());

        tvChooseType.setText(applyRejectedBean.getSealName());
        applySealTypeId = applyRejectedBean.getSealRegId();

        shSwitchView.setOn(TextUtils.equals("1", applyRejectedBean.getEmbedEquipOutFlag()));

        tvReason.setText(applyRejectedBean.getApplyReasonTypeName());
        applySealReasonId = applyRejectedBean.getApplyReasonTypeId();

        Glide.with(mContext).asBitmap().load(
                applyRejectedBean.getApplicantUserAvatar())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource,
                                                Transition<? super Bitmap> transition) {
                        ivAddUserPic.setImageBitmap(resource);
                    }
                });
        List<LocalImageHelper.LocalFile> files = new ArrayList<>();
        List<ApplyRejectedBean.ApplyDocPicListEntity> docs = applyRejectedBean.getApplyDocPicList();
        for (ApplyRejectedBean.ApplyDocPicListEntity doc : docs) {
            LocalImageHelper.LocalFile file = new LocalImageHelper.LocalFile();
            file.setApplyDocPicId(doc.getApplyDocPicId());
            file.setOriginalUri(doc.getPath());
            file.setThumbnailUri(doc.getPath());
            files.add(file);
        }
        imageScrollView.addFiles(files);

        tvPicNum.setText("文件拍照（已拍" + imageScrollView.getFiles().size() + "/100张）");

        etReason.setText(applyRejectedBean.getApplyReason());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalImageHelper.getInstance().release();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_apply_seal_stamp_time:
                showDataPickerDialog();
                break;
            case R.id.tv_apply_seal_stamp_start_time:
                showDataPickerDialogStartTime();
                break;
            case R.id.tv_apply_seal_stamp_end_time:
                showDataPickerDialogEndTime();
                break;
            case R.id.iv_apply_seal_add_user_pic:
                showPicSelectDialog();
                break;
            case R.id.ll_apply_seal_choose_seal_type:
                startActivityForResult(new Intent(mContext, ApplySealTypeActivity.class),
                        APPLY_SEAL_TYPE);
                break;
            case R.id.ll_apply_seal_reason:
                startActivityForResult(new Intent(mContext, ApplySealReasonActivity.class),
                        APPLY_SEAL_REASON);
                break;
            case R.id.ll_apply_seal_approval:
                if (isCommonUser && TextUtils.isEmpty(applySealTypeId)) {
                    ShowToast.shortTime("请先选择所用印章");
                    return;
                }
                startActivityForResult(new Intent(mContext, ApplySealApprovalActivity.class)
                        .putExtra("which_apply_seal_type_id", applySealTypeId), APPLY_SEAL_APPROVAL);
                break;
            case R.id.tv_apply_seal_submit:
                if (System.currentTimeMillis() - exitTime > 500) {
                    if (checkApplyReasonable()) {
                        sendRequestToApplyStamp();
                        exitTime = System.currentTimeMillis();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void showDataPickerDialog() {
        new TimePickerDialog.Builder().setCallBack(new OnDateSetListener() {
                @Override
            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                String time = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(
                        new Date(millseconds));
                tvStampTime.setText(time);
            }
        }).setCancelStringId("取消").setSureStringId("确定").setTitleStringId("请选择时间").setYearText("年")
                .setMonthText("月").setDayText("日").setHourText("时").setMinuteText("分").setCyclic(
                false).setMinMillseconds(System.currentTimeMillis()).setCurrentMillseconds(
                System.currentTimeMillis()).setThemeColor(
                ContextCompat.getColor(mContext, R.color.blue1)).setType(Type.YEAR_MONTH_DAY)
                .setWheelItemTextNormalColor(ContextCompat.getColor(mContext, R.color.grey1))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(mContext, R.color.blue1))
                .setWheelItemTextSize(18).build().show(getSupportFragmentManager(),
                "year_month_day");
    }

    private void showDataPickerDialogStartTime() {
        new TimePickerDialog.Builder().setCallBack(new OnDateSetListener() {
            @Override
            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(
                        new Date(millseconds));
                tvStampTimeStartTime.setText(time);
            }
        }).setCancelStringId("取消").setSureStringId("确定").setTitleStringId("请选择开始时间").setYearText(
                "年").setMonthText("月").setDayText("日").setHourText("时").setMinuteText("分")
                .setCyclic(false).setMinMillseconds(System.currentTimeMillis())
                .setCurrentMillseconds(System.currentTimeMillis()).setThemeColor(
                ContextCompat.getColor(mContext, R.color.blue1)).setType(Type.ALL)
                .setWheelItemTextNormalColor(ContextCompat.getColor(mContext, R.color.grey1))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(mContext, R.color.blue1))
                .setWheelItemTextSize(18).build().show(getSupportFragmentManager(),
                "year_month_day_hour_minute");
    }

    private void showDataPickerDialogEndTime() {
        new TimePickerDialog.Builder().setCallBack(new OnDateSetListener() {
            @Override
            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(
                        new Date(millseconds));
                tvStampTimeEndTime.setText(time);
            }
        }).setCancelStringId("取消").setSureStringId("确定").setTitleStringId("请选择结束时间").setYearText(
                "年").setMonthText("月").setDayText("日").setHourText("时").setMinuteText("分")
                .setCyclic(false).setMinMillseconds(System.currentTimeMillis())
                .setCurrentMillseconds(System.currentTimeMillis()).setThemeColor(
                ContextCompat.getColor(mContext, R.color.blue1)).setType(Type.ALL)
                .setWheelItemTextNormalColor(ContextCompat.getColor(mContext, R.color.grey1))
                .setWheelItemTextSelectorColor(ContextCompat.getColor(mContext, R.color.blue1))
                .setWheelItemTextSize(18).build().show(getSupportFragmentManager(),
                "year_month_day_hour_minute");
    }

    private void showPicSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View.inflate(mContext, R.layout.dialog_choose_image, null);
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        TextView tvgGallery = view.findViewById(R.id.tv_gallery);
        TextView tvCamera = view.findViewById(R.id.tv_camera);
        tvgGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent picture = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(picture, GALLERY_USER);
            }
        });
        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File imageFile = FilePathUtils.getImageFile();
                imagePath = imageFile.getAbsolutePath();
                LogUtil.d("ApplySeal Camera Pic Path: " + imagePath);
                Uri imageUri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".FileProvider", imageFile);
                } else {
                    imageUri = Uri.fromFile(imageFile);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, CAMERA_USER);
            }
        });
        dialog.show();
    }

    /**
     * 校验输入合理性
     * checkApplyReasonable
     *
     * @return reasonable
     */
    private boolean checkApplyReasonable() {

        if(isCommonUser){
            if (TextUtils.isEmpty(etName.getText().toString()) || TextUtils.isEmpty(etPhone.getText().toString())){
                ShowToast.shortTime("基本信息不全\n请去个人中心完善信息");
                return false;
            }
        } else {
            if (TextUtils.isEmpty(etName.getText().toString())) {
                ShowToast.shortTime("请填入申请人姓名");
                return false;
            }
            if (TextUtils.isEmpty(etPhone.getText().toString())) {
                ShowToast.shortTime("请填入手机号");
                return false;
            }
            if (!PhoneNumCheck.isMobileNo(etPhone.getText().toString())) {
                ShowToast.shortTime("请输入正确的手机号");
                return false;
            }
        }
        if (applyMode == APPLY_MODE_COUNT && TextUtils.isEmpty(etStampNum.getText().toString())) {
            ShowToast.shortTime("请填入用印次数");
            return false;
        }
        if (applyMode == APPLY_MODE_COUNT && TextUtils.isDigitsOnly(
                etStampNum.getText().toString()) && Integer.parseInt(
                etStampNum.getText().toString()) > 50) {
            ShowToast.shortTime("用印次数不能大于50");
            return false;
        }
        if (applyMode == APPLY_MODE_COUNT && TextUtils.equals(tvStampTime.getText(), "点击选择时间")) {
            ShowToast.shortTime("请选择用印时间");
            return false;
        }
        if (applyMode == APPLY_MODE_TIME && TextUtils.equals(tvStampTimeStartTime.getText(),
                "点击选择时间")) {
            ShowToast.shortTime("请选择用印起始时间");
            return false;
        }
        if (applyMode == APPLY_MODE_TIME && TextUtils.equals(tvStampTimeEndTime.getText(),
                "点击选择时间")) {
            ShowToast.shortTime("请选择用印结束时间");
            return false;
        }
        if (isCommonUser && TextUtils.isEmpty(applySealTypeId)) {
            ShowToast.shortTime("请选择用印类型！");
            return false;
        }
        if (imageScrollView.getFiles().isEmpty()) {
            ShowToast.shortTime("请选择文件图片！");
            return false;
        }
        if (TextUtils.isEmpty(applySealReasonId)) {
            ShowToast.shortTime("请选择用印理由！");
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK && requestCode != ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP) {
            return;
        }
        switch (requestCode) {
            case GALLERY_USER:
                Uri uri = data.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = this.getContentResolver().query(uri, filePathColumns, null, null, null);
                if (c == null) {
                    return;
                }
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePathColumns[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                userPathList.clear();
                userPathList.add(picturePath);
                Bitmap bitmapWithGallery = BitmapUtils.getScaleBitmap(this, picturePath);
                ivAddUserPic.setImageBitmap(bitmapWithGallery);
                break;
            case CAMERA_USER:
                userPathList.clear();
                userPathList.add(imagePath);
                Bitmap bitmapWithCamera = BitmapUtils.getScaleBitmap(this, imagePath);
                ivAddUserPic.setImageBitmap(bitmapWithCamera);
                break;
            case ImageUtils.REQUEST_CODE_GET_IMAGE_BY_CROP:
                if (LocalImageHelper.getInstance().isResultOk()) {
                    LocalImageHelper.getInstance().setResultOk(false);
                    List<LocalImageHelper.LocalFile> files = LocalImageHelper.getInstance()
                            .getCheckedItems();
                    imageScrollView.addFiles(files);
                    tvPicNum.setText("文件拍照（已拍" + imageScrollView.getFiles().size() + "/100张）");
                }
                break;
            case APPLY_SEAL_TYPE:
                if (data != null) {
                    applySealTypeId = data.getStringExtra("which_apply_seal_type_id");
                    String type = data.getStringExtra("which_apply_seal_type_name");
                    tvChooseType.setText(type);
                    String need = data.getStringExtra("which_apply_seal_type_need");
                    llChooseTypeNeed.setVisibility(
                            TextUtils.equals("0", need) ? View.VISIBLE : View.GONE);
                    LogUtil.d("选择用印 " + applySealTypeId + " " + type + " " + need);
                }
                break;
            case APPLY_SEAL_REASON:
                if (data != null) {
                    applySealReasonId = data.getStringExtra("which_apply_seal_reason_id");
                    String reason = data.getStringExtra("which_apply_seal_reason_name");
                    tvReason.setText(reason);
                    LogUtil.d("选择理由 " + applySealReasonId + " " + reason);
                }
                break;
            case APPLY_SEAL_APPROVAL:
                if (data != null) {
                    applySealApprovalId = data.getStringExtra("which_apply_seal_approval_id");
                    String name = data.getStringExtra("which_apply_seal_approval_name");
                    tvApproval.setText(name);
                    LogUtil.d("选择审核人 " + applySealApprovalId + " " + name);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发送申请
     * sendRequestToApplyStamp
     */
    private void sendRequestToApplyStamp() {
        Map<String, String> params = new HashMap<>();
        params.put("sealApplyId", sealApplyId);
        params.put("applyType", (applyMode == APPLY_MODE_COUNT) ? "COUNT_LIMIT" : "TIME_LIMIT");
        params.put("applicantUserName", etName.getText().toString());
        params.put("phone", etPhone.getText().toString());
        params.put("applyTimes", etStampNum.getText().toString());
        params.put("applyDate", tvStampTime.getText().toString());
        params.put("applyStartTimeReal", tvStampTimeStartTime.getText().toString());
        params.put("applyEndTimeReal", tvStampTimeEndTime.getText().toString());
        params.put("sealRegId", applySealTypeId);
        String embedEquipOutFlag = "1";
        LoginBean loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON),
                LoginBean.class);
        switch (loginBean.getEquipRegisterInfo().getEquipType()) {
            case "0":
                embedEquipOutFlag = shSwitchView.isOn() ? "1" : "0";
                break;
            case "1":
                embedEquipOutFlag = "1";
                break;
            default:
                if (isCommonUser) {
                    embedEquipOutFlag = !llChooseTypeNeed.isShown() ? "1" : shSwitchView
                            .isOn() ? "1" : "0";
                }
                break;
        }
        params.put("embedEquipOutFlag", embedEquipOutFlag);
        params.put("applyReasonTypeId", applySealReasonId);
        params.put("applyReason", etReason.getText().toString());
        params.put("curTaster", applySealApprovalId);
        params.put("docPicsCount", String.valueOf(imageScrollView.getFiles().size()));

        mProcessDialog.setTitle("正在提交用印申请").showNormal();
        postJsonEnqueue(UrlConstants.APPLY_STAMP, params, new OkHttpUtil.NetCallBack() {
            @Override
            public void onSucceed(String json) {
                mProcessDialog.dismiss();
                SealApplyIdBean bean = new Gson().fromJson(json, SealApplyIdBean.class);
                LoginBean loginBean = new Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON),
                        LoginBean.class);
                List<LocalImageHelper.LocalFile> files = imageScrollView.getFiles();

                if (userPathList.size() != 0) {
                    DbControl.getInstance().insertData("0", bean.getSealApplyId(),
                            loginBean.getUserLogin().getId(), "0", userPathList.get(0));
                }

                handleImg("1", bean.getSealApplyId(), loginBean.getUserLogin().getId(), "0", files);

                if (!DbControl.getInstance().hasUserByTelephone(etPhone.getText().toString())) {
                    DbControl.getInstance().insertUserData(etName.getText().toString(), etPhone.getText().toString());
                }
                else {
                    DbControl.getInstance().updateId(etPhone.getText().toString());
                }
            }

            @Override
            public void onFailed(String reason) {
                mProcessDialog.dismiss();
                ShowToast.shortTime(reason);
            }
        });
    }

    /**
     *  处理需上传的图片
     */
    private void handleImg(String type, String taskId, String userId, String backId,
                           List<LocalImageHelper.LocalFile> files) {
        DbControl.getInstance().insertData(type, taskId, userId, backId, files);
        List<ImageBean> images = DbControl.getInstance().selectAll();
        /*
          查看选择图片的路径
         */
        for (int i = 0; i < images.size(); i++) {
            LogUtil.d(images.get(i).getPaths());
        }

        ConnectivityManager connectMgr = (ConnectivityManager) SmartSeal.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectMgr.getActiveNetworkInfo();

        if (info != null) {
            if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                startService(new Intent(mContext, UploadImageService.class));
                finish();
            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                ShowDialog.showSelectDialog(mContext, "警告", "您当前正在使用移动网络，将会产生大量流量", "推荐在WIFI下上传",
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startService(new Intent(mContext, UploadImageService.class));
                                finish();
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        });
            }
        } else {
            finish();
        }
    }
}
